package com.suemi.missile.common.entity;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public interface Documentable {

  public String documentId();

  public void fromJson(JSONObject json);

  public JSONObject toJson();

  default public void fromJsonString(String str) {
    JSONObject json = JSONObject.parseObject(str);
    this.fromJson(json);
  }

  default public String toJsonString() {
    return toJson().toJSONString();
  }

  @SuppressWarnings("uncheck")
  default <T> T getField(String name){
    try {
      Field field = this.getClass().getDeclaredField(name);

      field.setAccessible(true);
      return (T) field.get(this);
    } catch (NoSuchFieldException | IllegalAccessException e) {
      return null;
    }
  }

  default List<String> fieldNames() {
    return Arrays.stream(this.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
  }
}
